package com.molichuxing.gateway.bff.order.services.impl;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.property.CarsBusinessTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.DingTalkUtil;
import com.molichuxing.gateway.bff.order.convertor.Convert;
import com.molichuxing.gateway.bff.order.entity.request.create.EnterpriseCarTransferCreateVo;
import com.molichuxing.gateway.bff.order.entity.response.EnterpriseCarTransferVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerContractVo;
import com.molichuxing.gateway.bff.order.services.EnterpriseCarTransferBffService;
import com.molichuxing.services.business.dto.request.create.EnterpriseCarTransferCreateBizDto;
import com.molichuxing.services.business.service.EnterpriseCarTransferBizService;
import com.molichuxing.services.infrastructure.dto.request.create.ContractEnterpriseCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.ContractFileCreateDto;
import com.molichuxing.services.infrastructure.service.CarService;
import com.molichuxing.services.infrastructure.service.ContractEnterpriseService;
import com.molichuxing.services.infrastructure.service.EnterpriseCarService;
import com.molichuxing.services.infrastructure.service.EnterpriseCarTransferService;
import com.molichuxing.services.infrastructure.service.IovCarService;
import com.molichuxing.services.infrastructure.service.OrderEnterpriseService;
import com.molichuxing.services.infrastructure.service.StockCarService;
import com.molichuxing.services.property.CarsOperateStatusEnum;
import com.molichuxing.services.property.ContractEnterpriseTypeEnum;
import com.molichuxing.services.property.StockCarCarStatusEnum;

/**
 * 企业车辆过户bff实现类
 *
 * @author liyiguang
 * @date 2020年6月4日
 */
@Service("enterpriseCarTransferBffService")
public class EnterpriseCarTransferBffServiceImpl implements EnterpriseCarTransferBffService {
	
	private static final Logger logger = LoggerFactory.getLogger(EnterpriseCarTransferBffServiceImpl.class);
	
	@Resource
	private EnterpriseCarTransferBizService enterpriseCarTransferBizService;
	
	@Resource
	private CarService carService;
	
	@Resource
	private EnterpriseCarService enterpriseCarService;
	
	@Resource
	private OrderEnterpriseService orderEnterpriseService;
	
	@Resource
	private StockCarService stockCarService;
	
	@Resource
	private ContractEnterpriseService contractEnterpriseService;
	
	@Resource
	private IovCarService iovCarService;
	
	@Resource
	private EnterpriseCarTransferService enterpriseCarTransferService;
	
	@Value("${profiles.active.explain}")
	private String active;
	
	
	@Override
	public Boolean create(EnterpriseCarTransferCreateVo createVo) throws Exception {
	
		CarDto carDto = carService.getCarByVin(createVo.getVin());
		if(null == carDto) {
			throw new BizException(101, "不存在该车辆信息");
		}
		OrderEnterpriseDto orderEnterprise = orderEnterpriseService.getEnterprise(createVo.getOrderCode());
		if(null == orderEnterprise) {
			throw new BizException(101, "不存在该订单信息");
		}
		Boolean flag = getEnterpriseCar(carDto,orderEnterprise);
		if(!flag) {
			throw new BizException(101, "该车辆信息不属于该订单");
		}
		//获取车辆实际里程
		Integer odoMileage = iovCarService.getOdoMileage(carDto.getVin());
		
		//修改车辆和仓储的运营状态 
		modifyCarStatus(carDto);
		//企业车辆过户
		createCarTransfer(carDto,orderEnterprise,createVo,odoMileage);
		//保存过户合同
		createContract(carDto,orderEnterprise,createVo);
		//车联网监控解除
		try {
			flag = iovCarService.vehicleIsAuth(createVo.getVin(),createVo.getOperateId(),createVo.getOperateName());
			if(!flag) {
				logger.error("车联网监控解除返回结果:"+flag);
				DingTalkUtil.exceptionSend(active+"车联网监控解除失败!");
			}
		}catch (BizException e) {
			logger.error("车联网监控解除失败:",e);
			DingTalkUtil.exceptionSend(active+e.getMessage());
		}catch (Exception e) {
			logger.error("车联网监控解除失败:",e);
			DingTalkUtil.exceptionSend(active+"车联网监控解除失败!");
		}
		return true;
	}

	/**
	 * 验证车辆是否属于该订单
	 * @param carDto
	 * @param orderEnterprise
	 * @return
	 */
	private Boolean getEnterpriseCar(CarDto carDto,OrderEnterpriseDto orderEnterprise) {
		List<EnterpriseCarDto> list = enterpriseCarService.getEnterpriseCar(orderEnterprise.getOrderCode());
		if(null == list || list.isEmpty()) {
			throw new BizException(101, "该订单信息错误");
		}
		for (EnterpriseCarDto dto : list) {
			if(dto.getCarId().equals(carDto.getId())) {
				return true;
			}
		}
		return false;
	}
	
	
	/**
	 * 修改车辆和仓储的运营状态
	 * @param carDto
	 * @return
	 */
	private Boolean modifyCarStatus(CarDto carDto) {
		CarModifyDto carModifyDto =new CarModifyDto();
		carModifyDto.setId(carDto.getId());
		carModifyDto.setBusinessType(CarsBusinessTypeEnum.BUY_OUT.getValue());
		carModifyDto.setStatus(CarsOperateStatusEnum.ALREADY_SOLD.getValue());
		carService.modify(carModifyDto);
		return stockCarService.modifyCarStatus(carDto.getId(),StockCarCarStatusEnum.ALREADY_SOLD.getValue());
	}
	
	/**
	 * 企业车辆过户
	 * @param carDto
	 * @param orderEnterprise
	 * @param createVo
	 * @param odoMileage
	 * @return
	 */
	private Boolean createCarTransfer(CarDto carDto,OrderEnterpriseDto orderEnterprise,EnterpriseCarTransferCreateVo createVo,Integer odoMileage) {
		EnterpriseCarTransferCreateBizDto createBizDto =new EnterpriseCarTransferCreateBizDto();
		createBizDto.setCarId(carDto.getId());
		createBizDto.setVin(carDto.getVin());
		createBizDto.setLicencePlate(carDto.getLicencePlate());
		createBizDto.setOrderCode(orderEnterprise.getOrderCode());
		createBizDto.setEnterpriseId(orderEnterprise.getEnterpriseId());
		createBizDto.setPayFees(createVo.getPayFees());
		createBizDto.setRemark(createVo.getRemark());
		createBizDto.setEndMileage(odoMileage);
		return enterpriseCarTransferBizService.create(createBizDto);
	}

	/**
	 * 保存过户合同
	 *
	 * @param carDto
	 * @param orderEnterprise
	 * @param createVo
	 * @throws Exception
	 */
	private void createContract(CarDto carDto, OrderEnterpriseDto orderEnterprise,
	                            EnterpriseCarTransferCreateVo createVo) throws Exception {

		ContractEnterpriseCreateDto contractDto = new ContractEnterpriseCreateDto();
		contractDto.setCarId(carDto.getId());
		contractDto.setOrderCode(orderEnterprise.getOrderCode());
		contractDto.setContractDate(LocalDate.now());
		contractDto.setContractType(ContractEnterpriseTypeEnum.TRANSFER_NAME_CONTRACT.getValue());
		contractDto.setContractUrls(Arrays.asList(
				new ContractFileCreateDto(createVo.getContractName(), createVo.getContractUrl())));
		contractEnterpriseService.createContract(contractDto);
	}

	/**
	 * 根据vin 获取企业车辆过户信息
	 *
	 * @param vin
	 * @return
	 */
	@Override
	public EnterpriseCarTransferVo getEnterpriseCarTransfer(String vin) {
		EnterpriseCarTransferDto dto = enterpriseCarTransferService.getEnterpriseCarTransferByVin(vin);
		EnterpriseCarTransferVo vo = Convert.toEnterpriseCarTransferVo(dto);
		ContractEnterpriseDto contractDto = contractEnterpriseService.getContractByOrderCode(vo.getOrderCode(),
				dto.getCarId(), ContractEnterpriseTypeEnum.TRANSFER_NAME_CONTRACT);
		if (null != contractDto && contractDto.getContractUrls() != null) {
			List<OrderDealerContractVo> contractVos = new ArrayList<>();
			for (ContractFileDto contractFileDto : contractDto.getContractUrls()) {
				OrderDealerContractVo contractVo = new OrderDealerContractVo();
				BeanUtils.copyProperties(contractFileDto, contractVo);
				contractVos.add(contractVo);
			}
			vo.setContractUrls(contractVos);
		}
		return vo;
	}
}
